<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace App\Views\Admin;

use Sun\Sun;
use Sun\Html;
use App\Models;

class Sql extends Main {
    public function __construct() {
        parent::__construct();
        $this->data_scene = 'Query';
    }

    public function QuerySwitchPage() {
        $switch = new Html\PageSwitch("SqlQuery");
        return $switch->ToHtml();
    }

    public function PageScene() {
        $db = new Models\DB();

        $num_rows = $this->data['Rows'];
        $p = $this->data['Page'];
        $offset = $num_rows * ($p - 1);
        $num_pages = 1;

        $div = new Html\Div();

        $query = $this->data['Query'];
        $query_count = "SELECT count(*) FROM ({$query}) s";
        $query_limit = "SELECT * FROM ({$query}) s LIMIT {$num_rows} OFFSET {$offset}";

        try {
            try {
                $rowCount = $db->SafeQuery($query_count)->fetch(Models\DB::FETCH_NUM);
                $rowCount = $rowCount[0];
                $res = $db->SafeQuery($query_limit);

                $content = new Html\QueryTable($res->fetchAll(Models\DB::FETCH_NUM),
                    Models\DB::FetchFields($res));
                $num_pages = ceil($rowCount / $num_rows);
                $div->Add(new Html\P())->Added()->Add(new Html\Text("Всего строк - {$rowCount}, страниц - {$num_pages}."));

            } catch (\Exception $e) {
                $res = $db->SafeQuery($query);
                $content = new Html\Text("Запрос выполнен. ");
            }

        } catch (\Exception $e) {
            $content = new Html\Text("Ошибочный запрос. ".$e->getMessage());
        }

        $div->Add($content);

        $query_res = "({ content: {$div->ToJSON()}, num_pages: {$num_pages} })";

        echo $query_res;
    }
}
